<?php

namespace app\modules\Product\models;

use Yii;
use app\modules\Cruise\models\Room;
use app\modules\Order\models\OrderRoom;

/**
 * This is the model class for table "product_room".
 *
 * @property integer $id
 * @property integer $room_id
 * @property string $price
 * @property string $inside_price
 * @property integer $user_id
 * @property string $created_at
 * @property string $updated_at
 */
class ProductRoom extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product_room';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'room_id', 'user_id', 'show', 'num','sell_out','people'], 'integer'],
            [['room_id'], 'required'],
            //[['price', 'inside_price'], 'number'],
            [['created_at', 'updated_at'], 'safe'],
        ];
    }


    // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
        }
    
        return parent::beforeSave($insert);
    }//}}}


 	// 保存后执行
	public function afterSave($insert, $changedAttributes){//{{{
		parent::afterSave($insert, $changedAttributes);

		//if($insert) {
		//	// 日志
		//	$desc = sprintf("配置舱房价格 %s", $this->name);
		//	Yii::$app->logs->info($this->id, 1, $desc, '' , 2);
		//}
	}//}}}



 
    //  获取对应舱房基础信息
    public function getRoom(){
        return $this->hasOne(Room::className(), ['id' => 'room_id']);
    }


    //  获取对应舱房价格信息
    public function getRoomPrice(){
        return $this->hasMany(ProductRoomPrice::className(), ['product_room_id' => 'id']);
    }


    //  获取对应舱房价格有效信息
    public function getRoomPriceShow(){
        return $this->hasMany(ProductRoomPrice::className(), ['product_room_id' => 'id'])->where(['show'=>1]);
    }

	// 获取舱房库存售出数量
	public function getStockNum(){
		$num = OrderRoom::find()->where(['product_id'=>$this->product_id, 'room_id'=>$this->id ,'status'=>1, 'stock'=>1])->count();
		return $num;
	}


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app', 'Product ID'),
            'room_id' => Yii::t('app', 'Room ID'),
            'price' => Yii::t('app', 'Price'),
            'inside_price' => Yii::t('app', 'Inside Price'),
            'user_id' => Yii::t('app', 'User ID'),
            //'created_at' => Yii::t('app', 'Created At'),
            //'updated_at' => Yii::t('app', 'Updated At'),
            'show' => Yii::t('app', 'Show'),
            'num' => Yii::t('app', 'Num'),
            //'people' => Yii::t('app', 'People Num'),
            'sell_out' => Yii::t('app', 'Sell Out'),
        ];
    }

}
